<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>大小码绑定</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <style type="text/css">
        th {
            text-align: center;
        }
        td {
            text-align: center;
        }

    </style>
</head>
<body style="background:white;">


<div class="row">
    <div class="col-lg-12 col-md-12">
        <div class="table-responsive">
            <table id="dama" class="table table-striped table-bordered table-hover table-condensed">
                <thead>
                <tr>
                    <th class="col-lg-3 col-md-3 col-sm-3 col-xs-3">序号</th>
                    <th class="col-lg-3 col-md-3 col-sm-3 col-xs-3">大码号</th>
                    <th class="col-lg-3 col-md-3 col-sm-3 col-xs-3">大码链接</th>
                    <th class="col-lg-3 col-md-3 col-sm-3 col-xs-3">大码操作</th>
                </tr>
                </thead>
                <tbody id="bList">

                </tbody>
            </table>
        </div>
    </div>
</div>


<div class="row">
    <div class="col-lg-12 col-md-12">
        <div class="table-responsive">
            <table id="xiaoma" class="table table-striped table-bordered table-hover table-condensed">
                <thead>
                <tr>
                    <th class="col-lg-3 col-md-3 col-sm-3 col-xs-3">序号</th>
                    <th class="col-lg-3 col-md-3 col-sm-3 col-xs-3">小码号</th>
                    <th class="col-lg-3 col-md-3 col-sm-3 col-xs-3">小码链接</th>
                    <th class="col-lg-3 col-md-3 col-sm-3 col-xs-3">小码操作</th>
                </tr>
                </thead>
                <tbody id="cList">

                </tbody>
            </table>
        </div>
    </div>
</div>


<div class="row">
    <div class="col-lg-12 col-md-12">
        <div class="table-responsive">
            <table class="table table-striped table-bordered table-hover table-condensed">
                <thead>
                <tr>
                    <th class="col-lg-3 col-md-3 col-sm-3 col-xs-3">序号</th>
                    <th class="col-lg-3 col-md-3 col-sm-3 col-xs-3">错码链接</th>
                    <th class="col-lg-3 col-md-3 col-sm-3 col-xs-3">错码原因</th>
                    <th class="col-lg-3 col-md-3 col-sm-3 col-xs-3">错码操作</th>
                </tr>
                </thead>
                <tbody id="eList">


                </tbody>
            </table>
        </div>
    </div>
</div>

<nav class="navbar navbar-default ">
</nav>

<nav class="navbar navbar-default ">
    <div class="container-fluid">
        <div class="form-inline navbar-form navbar-left" >

            <div class="form-group">
                <label for="code">防伪码</label>
                <input class="form-control typeahead" id="code" name="code" autofocus>
            </div>

            <div class="form-group">
                <label for="perBox">大码对应的小码数</label>
                <input class="form-control" type="number" id="perBox" name="perBox" placeholder="请输入大码对应的小码数">
            </div>
            <button role="btn" type="button"  id="download" class="btn btn-danger">离线下载</button>
        </div>

    </div>
</nav>

<div style="display: none" class="audio">
    <audio id="errorAudio" src="http://data3.huiyi8.com/2015/saraxuss/3/10/6.mp3">
        Your browser does not support the audio element.
    </audio>
</div>
<input STYLE="margin-right: 50px" type="button" value="报错" class="btn" id="btn">

<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/jquery.form/4.2.2/jquery.form.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<!--<script src="https://cdn.bootcss.com/xlsx/0.11.8/xlsx.core.min.js"></script>-->
<script src="https://cdn.bootcss.com/Base64/1.0.1/base64.min.js"></script>
<script src="https://cdn.bootcss.com/FileSaver.js/2014-11-29/FileSaver.min.js"></script>
<script src="https://cdn.bootcss.com/TableExport/4.0.10/js/tableexport.min.js"></script>


<script>
    var index1=0; //大码序号
    var index2=0; //小码序号
    var index3=0; //错码序号
    //错误提示
    $("#btn").click(function () {
        $("#errorAudio").get(0).play();
        index3=index3+1;
        var data = {
            "index3":index3,
            "code": "test",
            "message": "报错按钮测试"
        }
        $("#et").tmpl(data).appendTo($("#eList"));
    })
    function alertError(message) {
        //警报
        $("#errorAudio").get(0).play();
//        addErrorTdInput( $("#code").val(),message)
        var code = $("#code").val();
        index3=index3+1;
        var data = {
            "index3":index3,
            "code": code,
            "message": message
        }
        $("#et").tmpl(data).appendTo($("#eList"));
        $("#code").val("");//复原
    }

    //验证码的正确性
    function validateUrl(url) {
        //indexOf检查url中是否包含"code="和"boxCode=",没有包含返回-1
        if (url.indexOf("code=") < 0 ) {
            alertError("码规则有误，请检查");
            return false;
        }
        return true;
    }

    //是否是大箱
    function isBox(code) {
        //检查code是否包含"box"
        if (code.indexOf("/box") > -1) {
            return true;
        }
        return false;
    }

    //判断大小码是否有重复
    function validateRepeat(os, code) {
        var result = false;
        //遍历
        os.each(function () {
            if ($(this).find(".ctd").html() == code) {
                result = true;
            }
        })

        return result;
    }

    //是否是小箱
    function isCode(code) {
        if (code.indexOf("code") > -1) {
            return true;
        }
        return false;
    }

    //从防伪码链接中获取编号
    function getCodeFromCodeStr(code) {
        //截取字符串,从"="后面到结束
        var sc = code.substr(code.lastIndexOf("=") + 1, code.length);
        return sc;
    }


    $(function () {

        function checkBox(type) {
            //小码每箱数量
            var perBox = $("#perBox").val();
            var btdSize = $(".btr").length;//获取大箱td当前的数量
            var ctdSize = $(".ctr").length;//获取小箱td当前的数量
            if (btdSize == null) btdSize = 0;
            if (ctdSize == null) btdSize = 0;
            if(type=='box'){
                //如果已经有了必须要有对应的小箱数量才能录入
                if (btdSize != 0) {
                    if (btdSize * perBox != ctdSize) {
                        alertError("请录入小码!");
                        return false;
                    }
                }
            }else {
                if (btdSize == 0 || btdSize * perBox == ctdSize) {
                    alertError("请录入大码!");
                    return false;
                }
            }
            return true;
        }
        //按键触发
        $("#code").keypress(function (event) {

            //滚动条滚动
            var h = $(document).height()-$(window).height();
            $(document).scrollTop(h);
            //碰到回车
            var keynum = (event.keyCode ? event.keyCode : event.which);
            if (keynum != '13') {
                return;
            }

            //判断对应的数量是否为空
            var perBox = $("#perBox").val();
            if(perBox==null || ""==perBox){
                alertError("请输入大码对应的小码数!");
                return;
            }

            //获取链接
            var code = $(this).val();
            if (code == "confirm") {//自动提交
                confirmCodes();
                //TODO
                return;
            }
            //验证防伪码
            if (!validateUrl(code)) {
                return;
            }


            //处理code
            var c = getCodeFromCodeStr(code);//获取编号
            //模板数据装填
            var data = {
                "index1":index1,
                "c": c,
                "code": code
            }

            //处理大箱
            if (isBox(code)) {
                if(!checkBox('box')){
                    return;
                }
                //判断是否有重复
                if (validateRepeat($(".btr"), c)) {
                    alertError("重复录入大码!");
                    return;
                }
                index1=index1+1;
                data.index1=index1;
                $("#bList").append($("#bt").tmpl(data));
            } else if (isCode(code)) { //处理小箱子
                if(!checkBox('code')){
                    return;
                }
                //判断是否有重复
                if (validateRepeat($(".ctr"), c)) {
                    alertError("重复录入小码!");
                    return;
                }
                index2=index2+1;
                data.index1=index2;
                $("#cList").append($("#ct").tmpl(data));
            }


            $("#code").val("");
        });

        $(".table").delegate(".ajaxLink", "click", function () {
            var trClass = $(this).closest("tr").attr("class");
            if("btr"==trClass){
                index1=index1-1;
            }else if("ctr"==trClass){
                index2=index2-1;
            }else {
                index3=index3-1;
            }
            var objn =  $(this).closest("tr").next();
            $(this).closest("tr").remove();
            nextSequence(objn);

            //删除码列表一行后，后面的序号自动减1
            function nextSequence(obj){
                while (obj.length>0){
                    var text = $(obj).find('td').eq(0).text()
                    text = text -1;
                    $(obj).find('td').eq(0).text(text);
                    obj=obj.next();
                }
            }
        })

        function download(filename, text) {
            var element = document.createElement('a');
            element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
            element.setAttribute('download', filename);

            element.style.display = 'none';
            document.body.appendChild(element);

            element.click();

            document.body.removeChild(element);
        }


        function toSql(){
            let codes = []
            let boxCodes = []
            //小码
            $(".ctr").each(function () {
                codes.push($(this).find(".ctd").html())
            })
            //大码
            $(".btr").each(function () {
                boxCodes.push($(this).find(".ctd").html())
            })
            let sqls = []
            var perBox = $("#perBox").val();
            for (let i = 0; i < boxCodes.length; i++) {
                let start  = i*perBox
                let end = (i+1)*perBox
                if(end>codes.length){
                    end = codes.length
                }
                for (let j = start; j < end; j++) {
                    let strSql = "('1', '公司', '01', '管理员','暂未绑定','"+codes[j]+"','"+boxCodes[i]+"')"
                    if(j!=codes.length-1){
                        strSql+=","
                    }
                    sqls.push(strSql)
                }
            }
            let text = "insert into security_code(version,owner,agent_Code,recorder,goods_name,code,boxCode) values\r\n";
            sqls.forEach(sql=>{
                text = text+sql+"\r\n"
            })
            download("sec.sql",text)

        }

        //离线下载
        $("#download").click(function () {
            toSql()
            //判断是否有exportToTXT按钮
            if($(".tableexport-caption").length>0){
                return;
            }
            //首先验证码的完整性
            /*if(! checkBox('box')){
                return;
            }*/
            TableExport.prototype.charset = "charset=utf-8";
            TableExport(document.getElementsByTagName("table"), {
                headers: true,                              // (Boolean), display table headers (th or td elements) in the <thead>, (default: true)
                footers: true,                              // (Boolean), display table footers (th or td elements) in the <tfoot>, (default: false)
                formats: ['txt'],             // (String[]), filetype(s) for the export, (default: ['xls', 'csv', 'txt'])
                filename: 'id',                             // (id, String), filename for the downloaded file, (default: 'id')
                bootstrap: true,                           // (Boolean), style buttons using bootstrap, (default: true)
                exportButtons: true,                        // (Boolean), automatically generate the built-in export buttons for each of the specified formats (default: true)
                position: 'bottom',                         // (top, bottom), position of the caption element relative to table, (default: 'bottom')
                ignoreRows: null,                           // (Number, Number[]), row indices to exclude from the exported file(s) (default: null)
                ignoreCols: [0,2,3],                           // (Number, Number[]), column indices to exclude from the exported file(s) (default: null)
                trimWhitespace: true,                        // (Boolean), remove all leading/trailing newlines, spaces, and tabs from cell text in the exported file(s) (default: false)
            });
        })
    })

</script>

<!--大箱td模板-->
<script id="bt" type="text/x-jquery-tmpl">
    <tr class="btr" >
        <td style="vertical-align: middle">{{= index1}}</td>
        <td style="vertical-align: middle" class="ctd">{{= c}}</td>
        <td style="vertical-align: middle">{{= code}}</td>
        <td><a class="ajaxLink btn btn-danger default" data-role="delete" ><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除</a>
    </tr>




</script>

<!--小箱td模板-->
<script id="ct" type="text/x-jquery-tmpl">
  <tr class="ctr" style="vertical-align: middle">
    <td style="vertical-align: middle">{{= index1}}</td>
    <td style="vertical-align: middle" class="ctd">{{= c}}</td>
    <td style="vertical-align: middle" >{{= code}}</td>
    <td><a class="ajaxLink btn btn-danger default" data-role="delete" ><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除</a>
  </tr>




</script>

<!--错误模板-->
<script id="et" type="text/x-jquery-tmpl">
  <tr class="etr">
    <td style="vertical-align: middle">{{= index3}}</td>
    <td style="vertical-align: middle">{{= code}}</td>
    <td style="vertical-align: middle">{{= message}}</td>
    <td><a class="ajaxLink btn btn-danger default" data-role="delete" ><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除</a>
  </tr>




</script>


</body>
</html>